<?php

use SC\Setting\Setting;

$laravel_setting_cache = [];
$laravel_setting_loaded = false;


if (!\function_exists('setting')) {
    /**
     * 查询或更新设置项
     *
     * 查询：setting($key, $default=null) => $value
     *
     * 更新，不跟新数据库：setting([$key => $value])
     * 更新，且更新数据库：setting([$key => $value], true)
     */
    function setting($key, $default=null)
    {
        global $laravel_setting_cache;
        global $laravel_setting_loaded;

        //setter
        if (\is_array($key)) {
            foreach($key as $k=>$v) {
                $laravel_setting_cache[$k] = $v;
            }

            if ($default === true) {
                foreach($key as $k=>$v) {
                    Setting::updateOrCreate(['key' => $k], ['value' => $v]);
                }
            }
        } else {
            //getter
            if (!$laravel_setting_loaded) {
                $laravel_setting_loaded = true;
                foreach(Setting::all() as $setting) {
                    $laravel_setting_cache[$setting->key] = $setting->value;
                }
            }
            return $laravel_setting_cache[$key] ?? $default;
        }
    }
}

if (!function_exists("setting_from_db")) {
    /**
     * 从数据库中查询一条数据
     */
    function setting_from_db($key, $default=null) {
        $inst = Setting::where(['key' => $key])->first();
        return is_null($inst) ? $default : $inst->value;
    }
}